<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { Search, Finished, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

import { getDyListDataApi, pushDyOrder, Autopush, ReturnPrice } from "@/api/capture-dy"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { formatDateTime } from "@/utils"
import { useUserStore } from "@/store/modules/user"
import { useCommonStore } from "@/store/modules/common"
import useClipboard from "vue-clipboard3"
import { shortcuts } from "@/utils/dateSet"

defineOptions({
  name: "CaptureListDy"
})

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const userStore = useUserStore()
const commonStore = useCommonStore()

const loading = ref<boolean>(false)
const switchBoo = ref<boolean>(commonStore.openBtn)

// #region 查
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const searchFormRef = ref<FormInstance | null>(null)
const orderStatusList = ref<any>([
  {
    value: 1,
    label: "待确认/待支付-订单创建完毕"
  },
  {
    value: 105,
    label: "已支付"
  },
  {
    value: 2,
    label: "待发货"
  },
  {
    value: 101,
    label: "部分发货"
  },
  {
    value: 3,
    label: "已发货(全部发货)"
  },
  {
    value: 4,
    label: "已取消"
  },
  {
    value: 5,
    label: "已完成"
  }
])
// 搜索内容
const searchData = reactive<any>({
  time: "",
  id: "",
  status: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
// #endregion

const tableData = ref<any>([])
const getTableData = async () => {
  if (!searchData.time) {
    searchData.time = []
  }
  loading.value = true
  await getDyListDataApi({
    startTime: !searchData.id
      ? new Date(searchData.time[0]).getTime() / 1000 || new Date(new Date().toLocaleDateString()).getTime() / 1000
      : new Date(searchData.time[0]).getTime() / 1000 || "",
    endTime: !searchData.id
      ? new Date(searchData.time[1]).getTime() / 1000 || Math.floor(new Date().getTime() / 1000)
      : new Date(searchData.time[1]).getTime() / 1000 || "",
    userId: userStore.userInfo.user.id,
    orderId: searchData.id,
    status: searchData.status,
    // isSubmit: searchData.isSubmit,
    page: paginationData.currentPage,
    size: paginationData.pageSize
  })
    .then((res) => {
      console.log(res.data)
      paginationData.total = res.data.total
      tableData.value = res.data.list
      loading.value = false
    })
    .finally(() => {
      loading.value = false
    })
}

// #region 套餐
import { getComboDataApi } from "@/api/combo-jd"
const comboList = ref<any>([])
getComboDataApi({
  page: 1,
  size: 10000,
  type: "dy",
  userId: userStore.usernameID
}).then((res: any) => {
  comboList.value = res.data.list
})
// #endregion

// #region 查看详情
const formData = reactive<any>({ data: {} })
const seeState = ref<string>("")
const dialogVisible = ref<boolean>(false)
const handleSeeInfo = (row: any) => {
  seeState.value = "see"
  rowData(row, false)
  console.log(row, "查看详情")
}
// row通用
const rowData = async (row: any, PL: boolean) => {
  formData.data = row
  if (!PL) {
    dialogVisible.value = true
    dataArr.value.push(formData.data)
  } else {
    dataArr.value.push(row)
  }
}
// #endregion
//已提交禁选

const selectable = (row: any) => {
  return !(row.orderStatus == 1 || row.orderStatus == 4)
}

// #region 批量提交
const dataArr = ref<any>([])
const tableRef = ref<any>(null)
// 批量选择
const handleSelectionChange = (val: any) => {
  dataArr.value = []
  console.log(val, 1023)
  if (val.length) {
    val.forEach((item: any) => {
      rowData(item, true)
    })
  }
}
// 订单上传接口
const pushDy = async (data: any) => {
  console.log(data)
  await pushDyOrder(data, userStore.usernameID).then((res: any) => {
    // console.log(res, 1923)
    if (res.code == 200) {
      dataArr.value = []
      tableRef.value?.clearSelection()
      getTableData()
      ElMessage.success(res.data)
      dialogVisible.value = false
    }
  })
}
//单次提交
const handleAdd = (row: any) => {
  rowData(row, false)
}
const handlePushOne = () => {
  pushDy(dataArr.value)
}
//批量提交
const addItems = async () => {
  if (dataArr.value.length) await pushDy(dataArr.value)
  console.log("批量提交")
}
const autoOpen = (val: any) => {
  // console.log(val)
  commonStore.setOpenBtn(val)
  Autopush({ flag: val, userId: userStore.usernameID }).then((res) => {
    console.log(res)
  })
}
// #endregion

//  #region 清除规则报错信息
const formRef = ref<FormInstance | null>(null)
const currentUpdateId = ref<undefined | string>(undefined)
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  seeState.value = ""
  dataArr.value = []
  clearValidate()
}
// #endregion

//复制套餐编码

const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制！")
  } catch (e) {
    console.error(e)
  }
}

//手动退款
const handleReturn = (row: any) => {
  ElMessageBox.confirm(`正在进行订单号为：${row.orderId} 的退款操作，确认退款？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    ReturnPrice({ orderId: row.orderId, userId: userStore.userInfo.user.id }).then((res: any) => {
      console.log(res)
      getTableData()
    })
  })
}
//审核通过
// const handleReturnOK = (row: any) => {
//   ElMessageBox.confirm(`正在进行订单号为：${row.orderId} 的退款操作，确认退款？`, "提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning"
//   }).then(() => {
//     ReturnPriceOK({ orderId: row.orderId, userId: userStore.userInfo.user.id }).then((res: any) => {
//       console.log(res)
//       getTableData()
//     })
//   })
// }

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// #endregion
</script>
<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper" v-loading="loading">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="订单ID">
          <el-input v-model.trim="searchData.id" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="time" label="订单日期">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <!-- <el-form-item prop="isSubmit" label="是否提单">
          <el-select v-model="searchData.isSubmit" clearable placeholder="请选择" style="width: 200px">
            <el-option key="1" label="已提交" value="已提交" />
            <el-option key="2" label="未提交" value="未提交" />
          </el-select>
        </el-form-item> -->
        <el-form-item prop="status" label="状态">
          <el-select v-model="searchData.status" clearable placeholder="请选择" style="width: 200px">
            <el-option v-for="item in orderStatusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-form-item label="自动提交" style="font-size: 14px">
        <el-switch v-model="switchBoo" @change="autoOpen" />
      </el-form-item>
      <el-button type="primary" :icon="Finished" @click="addItems">批量提交</el-button>
    </el-card>
    <el-card shadow="never" v-loading="loading">
      <div class="table-wrapper">
        <el-table :data="tableData" @selection-change="handleSelectionChange" ref="tableRef">
          <el-table-column type="selection" :selectable="selectable" width="50" align="center" />
          <el-table-column prop="orderId" label="订单ID" align="center" />
          <el-table-column label="商品信息" align="center" width="300">
            <template #default="scope">
              <el-row>
                <el-col :span="8" style="text-align: center; vertical-align: middle">
                  <p><img :src="scope.row.productPic" alt="" width="50" height="50" /></p>
                </el-col>
                <el-col :span="16">
                  <!-- <p :title="item.goods_name" class="esp">{{ item.goods_name }}</p> -->
                  <!-- <p>{{ item.sku_id }}</p> -->
                  <p :title="scope.row.productName">{{ scope.row.productName }}</p>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="套餐匹配" align="center" width="360">
            <template #default="scope">
              <el-select v-model="scope.row.skuId" clearable filterable placeholder="请选套餐">
                <el-option
                  v-for="item in comboList"
                  :key="item.id"
                  :label="item.systemName"
                  :value="Number(item.code)"
                />
              </el-select>
              <el-link type="primary" style="margin-left: 10px" @click="copy(scope.row.skuId + '')"
                ><el-icon><DocumentCopy /></el-icon>复制编码</el-link
              >
            </template>
          </el-table-column>
          <el-table-column label="订单创建时间" width="180" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime * 1000) }}
            </template>
          </el-table-column>
          <el-table-column label="收件信息" align="center">
            <template #default="scope">
              <p>{{ scope.row.maskName }}</p>
              <p>{{ scope.row.maskPhone }}</p>
              <p :title="scope.row.maskAddress" class="esp">
                {{ scope.row.province }} {{ scope.row.city }} {{ scope.row.town }} {{ scope.row.street }}
                {{ scope.row.maskAddress }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="authorId" label="达人ID" align="center" />
          <el-table-column label="是否提单" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === '已提交'" style="color: #67c23a">已提交</span>
              <span style="color: red" v-else>未提交</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center" width="240">
            <template #default="scope">
              <el-select v-model="scope.row.orderStatus" style="width: 200px" disabled>
                <el-option v-for="item in orderStatusList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                text
                bg
                size="small"
                :disabled="scope.row.orderStatus == 1 || scope.row.orderStatus == 4"
                @click="handleAdd(scope.row)"
                >修改提交</el-button
              ><br />
              <el-button style="margin: 5px 0" type="primary" text bg size="small" @click="handleSeeInfo(scope.row)"
                >查看详情</el-button
              ><br />
              <el-button style="margin: 5px 0" type="primary" text bg size="small" @click="handleReturn(scope.row)"
                >手动退款</el-button
              >
              <!-- <br />
              <el-button style="margin: 5px 0" type="primary" text bg size="small" @click="handleReturnOK(scope.row)"
                >审核通过</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="[10, 20]"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" :title="seeState === 'see' ? '查看详情' : '提交'" @close="resetForm" width="60%">
      <el-form ref="formRef" :model="formData.data" label-width="100px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <div>
              <div style="padding-left: 20px">
                <el-form-item prop="orderId" label="订单ID">
                  <el-input v-model="formData.data.orderId" placeholder="请输入订单编号" disabled />
                </el-form-item>
                <el-form-item prop="createTime" label="创建时间">
                  <div class="el-input is-disabled">
                    <div class="el-input__wrapper">
                      <span class="el-input__inner">{{ formatDateTime(formData.data.createTime * 1000) }}</span>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item prop="orderStatus" label="订单状态">
                  <el-select
                    v-model="formData.data.orderStatus"
                    clearable
                    placeholder="请选择"
                    style="width: 200px"
                    :disabled="seeState === 'see'"
                  >
                    <el-option
                      v-for="item in orderStatusList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <h4>身份证信息:</h4>
                <el-form-item prop="idCardName" label="用户姓名">
                  <el-input
                    v-model="formData.data.idCardName"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <el-form-item prop="idCard" label="身份证号">
                  <el-input
                    v-model="formData.data.idCard"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <h4>订单备注:</h4>
                <el-form-item prop="remark" label="备注">
                  <el-input
                    v-model="formData.data.remark"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                    :rows="4"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div>
              <el-form-item prop="productName" label="套餐名">
                <el-input v-model="formData.data.productName" placeholder="请输入" type="textarea" disabled />
              </el-form-item>
              <el-form-item prop="productPic" label="套餐主图">
                <div class="demo-image__preview">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="formData.data.productPic"
                    :zoom-rate="1.2"
                    :initial-index="4"
                    fit="cover"
                  />
                </div>
              </el-form-item>
              <h4>收件信息:</h4>
              <div style="padding-left: 20px">
                <el-form-item prop="maskName" label="收货人姓名">
                  <el-input v-model="formData.data.maskName" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="phone" label="联系电话">
                  <el-input v-model="formData.data.phone" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <div v-if="seeState !== 'see'">
                  <el-form-item prop="province" label="省">
                    <el-input v-model="formData.data.province" placeholder="请输入" :disabled="seeState === 'see'" />
                  </el-form-item>
                  <el-form-item prop="city" label="市">
                    <el-input v-model="formData.data.city" placeholder="请输入" :disabled="seeState === 'see'" />
                  </el-form-item>
                  <el-form-item prop="town" label="区">
                    <el-input v-model="formData.data.town" placeholder="请输入" :disabled="seeState === 'see'" />
                  </el-form-item>
                  <el-form-item prop="street" label="街道">
                    <el-input v-model="formData.data.street" placeholder="请输入" :disabled="seeState === 'see'" />
                  </el-form-item>
                  <el-form-item prop="address" label="具体地址">
                    <el-input v-model="formData.data.address" placeholder="请输入" :disabled="seeState === 'see'" />
                  </el-form-item>
                </div>
                <div v-else>
                  <el-form-item prop="address" label="详细地址">
                    <div class="el-textarea is-disabled">
                      <span class="el-textarea__inner">
                        {{ formData.data.province }} {{ formData.data.city }} {{ formData.data.town }}
                        {{ formData.data.street }} {{ formData.data.address }}</span
                      >
                    </div>
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePushOne" v-if="seeState !== 'see'">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  .btn {
    width: 100%;
    height: 100%;
    display: flex;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.date-box {
  width: 340px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.pbox {
  line-height: 2em;
}
.flag {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.red {
  background: red;
}
.yellow {
  background: rgb(255, 220, 0);
}
.green {
  background: green;
}
.blue {
  background: blue;
}
.purple {
  background: purple;
}
.goodInfo {
  text-align: left;
}
.esp {
  /* width: 180px; */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}
</style>
